//
//  MLXNetworkManager.m
//  MLX
//
//  Created by SY on 2018/11/1.
//  Copyright © 2018年 SY. All rights reserved.
//

#import "MLXNetworkManager.h"
#import "MBProgressHUD+MLX.h"
#import "MLXMacroHeader.h"

static MLXNetworkManager *_networkManager;

@interface MLXNetworkManager ()
@property(nonatomic,weak) MBProgressHUD *hud;
@property(nonatomic,assign) BOOL isAlready;
@end

@implementation MLXNetworkManager

+(instancetype)allocWithZone:(struct _NSZone *)zone{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (_networkManager == nil) {
            _networkManager = [super allocWithZone:zone];
        }
    });
    return _networkManager;
}
+(instancetype)shareNetworkManager{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _networkManager = [[self alloc] init];
    });
    return _networkManager;
}
// 为了严谨，也要重写copyWithZone 和 mutableCopyWithZone
-(id)copyWithZone:(NSZone *)zone{
    return _networkManager;
}
-(id)mutableCopyWithZone:(NSZone *)zone{
    return _networkManager;
}
+(void)hideHud{
    if ([MLXNetworkManager shareNetworkManager].hud) {
        [[MLXNetworkManager shareNetworkManager].hud hide:YES];
    }
}

+(void)mlx_sendPostRequest:(NSString *)url parameters:(id)parameters hudText:(NSString *)hudText autoHudHide:(BOOL)isAutoHudHide hudView:(UIView *)hudView isQuery:(BOOL)isQuery success:(void(^)(id responseObject))successBlock failure:(void(^)(NSURLSessionTask *task, NSError *error, NSInteger statusCode))failureBlock{
    MBProgressHUD *hud;
    if (hudText!= nil) {
        [self hideHud];
        hud = [MBProgressHUD defaultMBProgressWithText:hudText view:hudView];
        [MLXNetworkManager shareNetworkManager].hud = hud;
    }
//    [SJNetworkManager sharedManager].isQuery = isQuery;
    [[SJNetworkManager sharedManager] sendPostRequest:url parameters:parameters success:^(id responseObject) {
        NSInteger statusCode = [responseObject[@"code"] integerValue];
        BOOL tokenOverdue = statusCode == 602 || statusCode == 601;
        if(hud && isAutoHudHide && !tokenOverdue) [hud hide:YES];
        if (hudText == nil && !tokenOverdue) [self hideHud];
        if (statusCode == 200) {
            !successBlock ?: successBlock(responseObject);
        }else if(tokenOverdue){//用户不存在  其实就是token不存在或过期
            if ([MLXNetworkManager shareNetworkManager].isAlready) {
                if(hud) [hud hide:YES];
                [self hideHud];
            }
            [self loginRequestSuccess:^{
                [self mlx_sendPostRequest:url parameters:parameters hudText:nil autoHudHide:isAutoHudHide hudView:hudView isQuery:YES success:successBlock failure:failureBlock];
            }];
        }else if(statusCode == 603){//账号在其他地方登陆
            [MBProgressHUD showNotice:@"您的账号在其他设备登陆" view:nil afterDelay:3.0f];
        }else if(statusCode == 500){
            [MBProgressHUD showNotice:@"网络请求繁忙，请稍后再试" view:nil];
        }else{
            !failureBlock ?: failureBlock(nil,nil,[responseObject[@"code"] integerValue]);
            [MBProgressHUD showNotice:responseObject[@"msg"] view:nil];
        }
    } failure:^(NSURLSessionTask *task, NSError *error, NSInteger statusCode) {
        if(hud) [hud hide:YES];
        if (hudText == nil) [self hideHud];
        if (statusCode == -999)  return;//取消
        if (statusCode == -1009) {
            //似乎已断开与互联网的连接
            [MBProgressHUD showNotice:@"当前网络不可用，请检查后再试" view:nil];
        }else if (statusCode == -1001) {
           [MBProgressHUD showNotice:@"网络请求繁忙，请稍后再试" view:nil];
        } else {
            [MBProgressHUD showNotice:@"系统繁忙，请稍候再试" view:nil];
        }
        !failureBlock ?: failureBlock(task,error,statusCode);
    }];
    
}
+(void)mlx_sendGetRequest:(NSString *)url parameters:(id)parameters hudText:(NSString *)hudText autoHudHide:(BOOL)isAutoHudHide hudView:(UIView *)hudView isQuery:(BOOL)isQuery success:(void(^)(id responseObject))successBlock failure:(void(^)(NSURLSessionTask *task, NSError *error, NSInteger statusCode))failureBlock{
    MBProgressHUD *hud;
    if (hudText!= nil) {
        [self hideHud];
        hud = [MBProgressHUD defaultMBProgressWithText:hudText view:hudView];
        [MLXNetworkManager shareNetworkManager].hud = hud;
    }
//    [SJNetworkManager sharedManager].isQuery = isQuery;
    [[SJNetworkManager sharedManager] sendGetRequest:url parameters:parameters success:^(id responseObject) {
        NSInteger statusCode = [responseObject[@"code"] integerValue];
        BOOL tokenOverdue = statusCode == 602 || statusCode == 601;
        if(hud && isAutoHudHide && !tokenOverdue) [hud hide:YES];
        if (hudText ==nil && !tokenOverdue) [self hideHud];
        if (statusCode == 200) {
            !successBlock ?: successBlock(responseObject);
        }else if(tokenOverdue){//用户不存在  其实就是token不存在或过期
            [self loginRequestSuccess:^{
               [self mlx_sendGetRequest:url parameters:parameters hudText:nil autoHudHide:isAutoHudHide hudView:hudView isQuery:YES success:successBlock failure:failureBlock];
            }];
        }else if(statusCode == 603){//账号在其他地方登陆
            [MBProgressHUD showNotice:@"您的账号在其他设备登陆" view:nil afterDelay:3.0f];
        }else if(statusCode == 500){
            [MBProgressHUD showNotice:@"网络请求繁忙，请稍后再试" view:nil];
        }else{
            !failureBlock ?: failureBlock(nil,nil,[responseObject[@"code"] integerValue]);
            [MBProgressHUD showNotice:responseObject[@"msg"] view:nil];
        }
    } failure:^(NSURLSessionTask *task, NSError *error, NSInteger statusCode) {
        if(hud) [hud hide:YES];
        if (hudText ==nil) [self hideHud];
        if (statusCode == -999)  return;//取消
        if (statusCode == -1009) {
            //似乎已断开与互联网的连接
            [MBProgressHUD showNotice:@"当前网络不可用，请检查后再试" view:nil];
        }else if (statusCode == -1001) {
            [MBProgressHUD showNotice:@"网络请求繁忙，请稍后再试" view:nil];
        } else {
            [MBProgressHUD showNotice:@"系统繁忙，请稍候再试" view:nil];
        }
        !failureBlock ?: failureBlock(task,error,statusCode);
    }];
}
+(void)mlx_cancelCurrentRequestWithUrl:(NSString *)Url{
    [[SJNetworkManager sharedManager] cancelCurrentRequestWithUrl:Url];
}
+ (void)mlx_addCustomHeader:(NSDictionary *_Nonnull)header{
    [[SJNetworkManager sharedManager] addCustomHeader:header];
}

+(void)loginRequestSuccess:(void(^)(void))successBlock{

}
#pragma mark -重新登陆
+(void)loginRefreshSuccess:(void(^)(void))successBlock{
   
}
#pragma makr - 刷新Token
+(void)tokenRefreshSuccess:(void(^)(void))successBlock{
    
}
+(void)saveUserModelToken:(id)responseObject{
    
}
@end
